/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jasoet.swing.cellrenderer;

import java.awt.Component;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author Deny Prasetyo
 */
public class ImageTableCellRenderer extends DefaultTableCellRenderer {

    private String imageLocation = "/org/jasoet/swing/images/";

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
            JLabel component = new JLabel();
            URL resource = getClass().getResource(imageLocation + value);
            ImageIcon imageIcon = new ImageIcon(resource);

            component.setIcon(imageIcon);
            component.setText("");
            component.setHorizontalAlignment(SwingConstants.CENTER);
            int currentHeight = table.getRowHeight(row);
            int currentRowWidth = table.getColumnModel().getColumn(column).getPreferredWidth();

            if (currentHeight < imageIcon.getIconHeight()) {
                table.setRowHeight(row, imageIcon.getIconHeight());
            }
            if (currentRowWidth < imageIcon.getIconWidth()) {
                table.getColumnModel().getColumn(column).setPreferredWidth(imageIcon.getIconWidth());
            }

            return component;
        } else {
            JLabel component = new JLabel();

            component.setText("" + value);
            component.setHorizontalAlignment(SwingConstants.CENTER);
            table.setRowHeight(row, 16);


            return component;
        }
    }
}
